<template>
  <div class="register-container">
    <TopView />
    <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="login-form" autocomplete="on" label-position="right">
      <div class="title-container">
        <h3 class="title">{{ $t('login.shakingEmperorUserRegistration') }}</h3>
      </div>
      <el-tabs v-model="registerForm.name_api_type" @tab-click="handleTagClick">
        <el-tab-pane name="email">
          <span slot="label" :class="registerForm.name_api_type=='email'?'register-tab-active':'register-tab'">{{ $t('login.emailRegistration') }}</span>
          <el-form-item prop="email">
            <div slot="label"><i style="color: #ff4949">*</i> {{ $t('login.email') }}</div>
            <el-input v-model="registerForm.email" :placeholder="$t('login.pleaseEnterContent')" class="input-with-select">
              <el-button slot="append" :disabled="emailCodeDisabled" @click="onEmailCode">{{ emailCodeText }}</el-button>
            </el-input>
          </el-form-item>
          <el-form-item prop="code" :label="$t('login.verificationCode')">
            <el-input v-model="registerForm.code" />
          </el-form-item>
          <el-form-item prop="password" :label="$t('login.password')">
            <el-input v-model="registerForm.password" :type="passwordType" autocomplete="off" />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
          <el-form-item prop="password_confirm" :label="$t('login.confirmPassword')">
            <el-input v-model="registerForm.password_confirm" type="password" autocomplete="off" />
          </el-form-item>

        </el-tab-pane>
        <el-tab-pane name="mobile">
          <span slot="label" :class="registerForm.name_api_type=='mobile'?'register-tab-active':'register-tab'">{{ $t('login.mobileNumberRegistration') }}</span>
          <el-form-item prop="mobile">
            <div slot="label"><i style="color: #ff4949">*</i> {{ $t('login.phoneNumber') }}</div>
            <el-input v-model="registerForm.mobile" :placeholder="$t('login.pleaseEnterContent')" class="input-with-select">
              <template slot="append">
                <el-button :disabled="mobileCodeDisabled" @click="onMobileCode">
                  {{ mobileCodeText }}

                </el-button>
              </template>

            </el-input>
          </el-form-item>
          <el-form-item prop="code" :label="$t('login.verificationCode')">
            <el-input v-model="registerForm.code" />
          </el-form-item>
          <el-form-item prop="password" :label="$t('login.password')">
            <el-input v-model="registerForm.password" :type="passwordType" autocomplete="off" />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
          <el-form-item prop="password_confirm" :label="$t('login.confirmPassword')">
            <el-input v-model="registerForm.password_confirm" type="password" autocomplete="off" />
          </el-form-item>

        </el-tab-pane>
      </el-tabs>
      <el-form-item prop="agreement" label=" ">
        <div style="display: flex">
          <div>
            <el-checkbox v-model="registerForm.agreement" :label="$t('login.checkRegistrationAgreement')" name="agreement" />
          </div>
          <div style="padding-left: 10px">
            <el-link style="color: #fff" @click="onRegistrationAgreement">{{ $t('login.registrationAgreementContent') }}</el-link>
          </div>
        </div>
      </el-form-item>
      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleRegister">{{ $t('login.registerNow') }}</el-button>

      <div class="div-register">
        <div class="register-title">
          <router-link to="/login">
            {{ $t('login.loginNow') }}
          </router-link>
        </div>
      </div>
    </el-form>
    <BottomView />
    <el-dialog
      :title="$t('login.registrationAgreementContent')"
      :visible.sync="agreementDialogVisible"
      width="90%"
    >
      <div style="padding: 10px">
        1、注册账号不得用来做违法乱纪的事<br>
        2、注册账号不得用来刷机平台系统<br>
        3、平台支付暂时只有微信支付和支付宝支付<br>
        4、平台主要是用来管理网站数据的系统<br>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="agreementDialogVisible = false">返回</el-button>
      </div>
    </el-dialog>
    <WebsiteStatistics />
  </div>
</template>

<script>
import { register } from '@/api/merchant'
import { Message } from 'element-ui'
import { loginMobileCode, loginEmailCode } from '@/api/code'
import BottomView from '@/views/bottom/index'
import TopView from '@/views/login/components/TopView'
import WebsiteStatistics from '@/components/WebsiteStatistics'

export default {
  name: 'Register',
  components: { BottomView, TopView, WebsiteStatistics },
  data() {
    const validateAgreement = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.$t('login.pleaseCheckTheRegistrationAgreement')))
      } else {
        callback()
      }
    }
    return {
      registerForm: {
        name_api_type: 'email',
        name_api: '',
        code: '',
        password: '',
        password_confirm: '',
        agreement: false,
        mobile: '',
        email: ''
      },
      registerRules: {
        password: [{ required: true, message: this.$t('login.cannotBeEmpty'), trigger: 'blur' }],
        password_confirm: [{ required: true, message: this.$t('login.cannotBeEmpty'), trigger: 'blur' }],
        code: [{ required: true, message: this.$t('login.cannotBeEmpty'), trigger: 'blur' }],
        agreement: [{ required: true, trigger: 'blur', validator: validateAgreement }]
      },
      passwordType: 'password',
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      mobileCodeText: this.$t('login.sendVerificationCode'),
      emailCodeText: this.$t('login.sendVerificationCode'),
      mobileCodeDisabled: false,
      emailCodeDisabled: false,
      codeTime: Date.now() + 1000 * 60 * 5,
      agreementDialogVisible: false
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    handleTagClick(tab, event) {
      this.registerForm.name_api_type = tab.name
    },
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.registerForm.name_api_type === 'mobile') {
            this.registerForm.name_api = this.registerForm.mobile
          } else {
            this.registerForm.name_api = this.registerForm.email
          }

          var data = this.registerForm
          if (this.registerForm.agreement) {
            data.agreement = 1
          } else {
            data.agreement = 0
          }
          var _this = this
          register(data)
            .then((res) => {
              Message({
                message: res.message,
                type: 'success',
                duration: 2 * 1000,
                onClose() {
                  _this.$router.push({ path: _this.redirect || '/login', query: _this.otherQuery })
                }
              })
              // _this.loading = false
            })
            .catch((res) => {
              _this.loading = false
              return false
            })
        } else {
          return false
        }
      })
    },
    startModelCountdown() {
      let seconds = 60 * 5 // 设置倒计时的秒数

      const timer = setInterval(() => {
        if (seconds > 0) {
          this.mobileCodeText = `${seconds}s` // 更新显示的倒计时文本
          seconds-- // 每次递减1秒
        } else {
          clearInterval(timer) // 当倒计时结束时清除定时器
          this.mobileCodeText = this.$t('login.sendVerificationCode') // 可选：将倒计时文本重置为特定内容
          this.mobileCodeDisabled = false
        }
      }, 1000) // 每隔1秒执行一次
    },
    startEmailCountdown() {
      let seconds = 60 * 5 // 设置倒计时的秒数

      const timer = setInterval(() => {
        if (seconds > 0) {
          this.emailCodeText = `${seconds}s` // 更新显示的倒计时文本
          seconds-- // 每次递减1秒
        } else {
          clearInterval(timer) // 当倒计时结束时清除定时器
          this.emailCodeText = this.$t('login.sendVerificationCode') // 可选：将倒计时文本重置为特定内容
          this.emailCodeDisabled = false
        }
      }, 1000) // 每隔1秒执行一次
    },
    onMobileCode() {
      var _this = this
      if (!this.registerForm.mobile) {
        Message({
          message: this.$t('login.pleaseFillInYourPhoneNumberFirst'),
          type: 'error',
          duration: 1 * 1000
        })
        return
      }
      this.mobileCodeDisabled = true
      loginMobileCode({
        type: 'registered',
        mobile: this.registerForm.mobile
      }).then(res => {
        this.startModelCountdown()
        Message({
          message: this.$t('login.successfullySentPleaseCheck'),
          type: 'success',
          duration: 1 * 1000
        })
      }).catch(res => {
        setTimeout(() => {
          _this.mobileCodeDisabled = false
        }, 2000)
      })
    },
    onEmailCode() {
      var _this = this
      if (!this.registerForm.email) {
        Message({
          message: this.$t('login.pleaseFillInYourEmailFirst'),
          type: 'error',
          duration: 1 * 1000
        })
        return
      }
      this.emailCodeDisabled = true
      loginEmailCode({
        type: 'registered',
        email: this.registerForm.email
      }).then(res => {
        this.startEmailCountdown()
        Message({
          message: this.$t('login.successfullySentPleaseCheck'),
          type: 'success',
          duration: 1 * 1000
        })
      }).catch(res => {
        setTimeout(() => {
          _this.emailCodeDisabled = false
        }, 2000)
      })
    },
    onRegistrationAgreement() {
      this.agreementDialogVisible = true
    }
  }
}
</script>
<style lang="scss" scoped>
$bg:#113b7b;
$dark_gray:#889aa4;
$light_gray:#eee;

.register-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;

  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }
  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .div-register{
    position: relative;
    height: 20px;
    .register-title{
      position: absolute;
      right: 0;
      bottom: 6px;
      color: #fff;
    }
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .register-tab{
    color: #fff;
  }
  .register-tab-active{
    color: #1890ff;
  }
}

</style>
